<template>
  <div>
    <a-modal
      width="850px"
      centered="true"
      :visible="visible"
      :confirm-loading="loading"
      :forceRender="true"
      :maskClosable="false"
      title="新增模型"
      :body-style="{ paddingBottom: '8px', height: '600px', overflow: 'hidden', overflowY: 'scroll'}"
      @update:visible="updateVisible"
      @close="updateVisible(false)"
    >
      <div>
        <a-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }"
        >
          <div class="card-title card-title-background">基础信息</div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="测试文件:" name="testFile">
                <a-input v-model:value="formData.testFile" placeholder="请输入测试文件" allow-clear />
              </a-form-item>
              <a-form-item label="资产名称:" name="modelName">
                <a-input v-model:value="formData.modelName" placeholder="请输入资产名称" allow-clear />
              </a-form-item>
              <a-form-item label="资产所属:" name="dept">
                <a-input v-model:value="formData.dept" placeholder="请输入资产所属" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="资产分类:" name="classify">
                <a-select v-model:value="formData.classify" placeholder="请选择资产分类" allow-clear>
                  <a-select-option :value="-1">全部分类</a-select-option>
                  <a-select-option
                    v-for="item in options.classify"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="作者:" name="author">
                <a-input v-model:value="formData.author" placeholder="请输入作者" allow-clear autocomplete="off" />
              </a-form-item>
              <a-form-item label="备注:" name="remark">
                <a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear autocomplete="off" />
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            自动精简
            <a-tooltip title="1、Brep精简可以转换B-Rep模型和混合模型（B-Rep和polygon）2、通过自动配置简化算法和参数，识别模型特征，通过快捷粗粒度的方式简化模型的几何形状（面和三角形）。建议无CAD基础的用户使用">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="simplify">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.simplify" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.simplify">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="精简程度"
                name="brepRemoveLevel"
              >
                <a-radio-group
                  v-model:value="formData.brepRemoveLevel"
                  button-style="solid"
                >
                  <a-radio-button :value="1">低</a-radio-button>
                  <a-radio-button :value="2">中</a-radio-button>
                  <a-radio-button :value="3">高</a-radio-button>
                </a-radio-group>
                <a-tooltip title="控制简化的激进性，通过停用一致性检查来反映，越高代表精简程度越激进，删除的面越多，对应的模型会越小，但精细度会更低，无效几何的风险越高">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="精简尺寸"
                name="brepRemoveSize"
              >
                <a-radio-group
                  v-model:value="formData.brepRemoveSize"
                  button-style="solid"
                >
                  <a-radio-button :value="1">小</a-radio-button>
                  <a-radio-button :value="2">中</a-radio-button>
                  <a-radio-button :value="3">大</a-radio-button>
                </a-radio-group>
                <a-tooltip title="精简的尺寸，越高代表精简程度越激进，对应的模型会越小，但精细度会更低">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            孔去除
            <a-tooltip title="此参数可移除盲孔和通孔，低于阈值（公差）的实体会被移除，孔去除器仅适用于入口由内线限制的孔（即单面孔）">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="holeRemoverSimplify">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.holeRemoverSimplify" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.holeRemoverSimplify">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="对角线公差"
                name="holeRemoveDiagonalTolerance"
              >
                <a-input-number
                  v-model:value="formData.holeRemoveDiagonalTolerance"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="删除所有小于给定参数的实体">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="范围公差"
                name="holeRemoveRangeTolerance"
              >
                <a-input-number
                  v-model:value="formData.holeRemoveRangeTolerance"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="应删除至少一个范围小于给定参数的实体">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="体积公差"
                name="holeRemoveVolumeTolerance"
              >
                <a-input-number
                  v-model:value="formData.holeRemoveVolumeTolerance"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="删除所有小于给定参数的零件">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="干扰检查"
                name="holeRemoveInterferenceCheck"
              >
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.holeRemoveInterferenceCheck" />
                <a-tooltip title="执行干扰检测，会提高模型的质量">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            内部面体去除
            <a-tooltip title="此参数根据对象的可见性起作用。从大多数视角和视点看不见的实体将被移除。用线性和角度公差控制，它相应地定义了两个视点之间的最大距离和两个视角之间角度的最大值。公差越大，则简化越粗糙">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="internalFacesRemoverSimplify">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.internalFacesRemoverSimplify" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.internalFacesRemoverSimplify">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="角度公差"
                name="internalFacesRemoveAngleTolerance"
              >
                <a-input-number
                  v-model:value="formData.internalFacesRemoveAngleTolerance"
                  :min="0"
                  :max="Math.PI"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="视线方向间无法区分的最大角度值">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="线性公差"
                name="internalFacesRemoveLinearTolerance"
              >
                <a-input-number
                  v-model:value="formData.internalFacesRemoveLinearTolerance"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="模型表面两个点之间不可区分的最大距离">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="删除不可见面"
                name="internalFacesRemoveInvisibleRemove"
              >
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.internalFacesRemoveInvisibleRemove" />
                <a-tooltip title="只删除所有共享实例中不可见的面">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            小实体去除
            <a-tooltip title="小实体去除">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="smallBodiesSimplify">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.smallBodiesSimplify" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.smallBodiesSimplify">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="质量阈值"
                name="smallBodiesRemoveThreshold"
              >
                <a-input-number
                  v-model:value="formData.smallBodiesRemoveThreshold"
                  :min="0"
                  :max="Math.PI"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="删除小于阈值的所有实体，当2.3,1取值为true才起作用">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="阈值"
                name="smallBodiesRemoveLinearTolerance"
              >
                <a-input-number
                  v-model:value="formData.smallBodiesRemoveLinearTolerance"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100px !important;"
                />
                <a-tooltip title="删除所有小于AABB长度的实体">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="感知"
                name="smallBodiesRemoveVisualQualityAware"
              >
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.smallBodiesRemoveVisualQualityAware" />
                <a-tooltip title="为ture表示不影响视觉质量才删除">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            Mesh精简
            <a-tooltip title="1. Mesh精简，允许处理polygon的模型，减少模型中的三角形数量。建议无CAD基础的用户使用，只修改简化程度即可。2. 支持的格式：FBX、DXF、glTF、PRC、U3D、VRML、X3D、STL、OBJ、PLY3D XML、3D FDF、3DS、3MF等。">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="meshSimplify">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.meshSimplify" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.meshSimplify">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="精简方式"
                name="meshSimpleType"
              >
                <a-select v-model:value="formData.meshSimpleType" style="width: 100px !important">
                  <a-select-option
                    v-for="itemT in options.meshSimpleType"
                    :key="itemT.value"
                    :value="itemT.value"
                  >
                    {{itemT.name}}
                  </a-select-option>
                </a-select>
                <a-tooltip title="精简方式">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="强制简化"
                name="meshSimpleForce"
              >
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.meshSimpleForce" />
                <a-tooltip title="当视觉质量不太重要时（比如只想确定模型大概是什么）可以启用强制简化，模型会非常精简，但精度会粗糙，甚至会打破模型的连接性（比如出现孔洞、网格边界的重大改变），不建议用于表示图纸几何的网格或未确保闭合性生成的网格">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24" v-if="formData.meshSimpleType === 1">
              <a-form-item
                label="程度"
                name="meshSimpleLevel"
              >
                <a-radio-group
                  v-model:value="formData.meshSimpleLevel"
                  button-style="solid"
                >
                  <a-radio-button :value="1">低</a-radio-button>
                  <a-radio-button :value="2">中</a-radio-button>
                  <a-radio-button :value="3">高</a-radio-button>
                </a-radio-group>
                <a-tooltip title="表示多少个三角形会被移除，low表示删除更少的三角形，则轻量化模型精度的更高，但文件更大">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" :xs="24" v-if="formData.meshSimpleType === 2">
              <a-form-item
                label="偏离值"
                name="meshSimpleValue"
              >
                <a-slider
                  v-model:value="formData.meshSimpleValue"
                  :min="0"
                  :max="20000"
                  :step="1"
                  style="width: 150px !important;"
                />
                <a-input-number v-model:value="formData.meshSimpleValue" :min="1" :max="20000" :step="1" style="margin-left: 10px;width: 80px !important;" />
                <a-tooltip title="1、如果启用该值，简化程度参数将不起作用。2、以毫米为单位的精确偏差值。表示原始网格上的点与生成的网格上的相应点。之间的距离上限，值越大代表轻量化越激进，文件越小。">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="card-title card-title-background">
            LOD程度测试
            <a-tooltip title="LOD程度测试中...">
              <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
            </a-tooltip>
          </div>
          <a-row :gutter="8">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item label="是否启用" name="isPreferredLOD">
                <a-switch checked-children="是" un-checked-children="否" v-model:checked="formData.isPreferredLOD" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="8" v-if="formData.isPreferredLOD">
            <a-col :md="12" :sm="24" :xs="24">
              <a-form-item
                label="程度"
                name="polyPreferredLOD"
              >
                <a-radio-group
                  v-model:value="formData.polyPreferredLOD"
                  button-style="solid"
                >
                  <a-radio-button :value="1">粗糙</a-radio-button>
                  <a-radio-button :value="2">中等</a-radio-button>
                  <a-radio-button :value="3">完美</a-radio-button>
                  <a-radio-button :value="4">任意</a-radio-button>
                </a-radio-group>
                <a-tooltip title="LOD程度">
                  <question-circle-outlined style="vertical-align: -3px; margin-left: 10px" />
                </a-tooltip>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <template #footer>
        <a-button @click="updateVisible(false)">取消</a-button>
        <a-button type="primary" @click="onSubmitClick" :loading="loading">确认提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {reactive, ref, watch, onMounted} from 'vue';
  import {useRoute, useRouter} from 'vue-router';
  import * as options from '/@/utils/options';
  import {ModelMgmtApi} from '/@/api/datadigital/modelMgmt/ModelMgmtApi';
  import {message} from 'ant-design-vue';

  const props = defineProps<{
    // 弹窗是否打开
    visible: Boolean;
    // 修改回显的数据
    data?: Object;
  }>();

  const emits = defineEmits<{
    (e: 'update:visible', visible: boolean): void;
    (e: 'done'): void;
  }>();

  const state = reactive({
    form: {},
  });

  // ref
  // const formRef = ref(null);

  const updateVisible = (value: boolean) => {
    emits('update:visible', value);
  };

  // 初始化
  const init = () => {
    if (props.data) {
      state.form = Object.assign({}, props.data);
    } else {
      state.form = {};
    }
    /*if (formRef.value && formRef.value.$refs.formRef) {
      formRef.value.$refs.formRef.clearValidate();
    }*/
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  };

  onMounted(() => {
    init();
  });

  watch(
    () => props.data,
    (val) => {
      init();
    },
  );

  const route = useRoute();
  const router = useRouter();
  const formRef = ref<any>();
  const formData = ref<any>({
    holeRemoveInterferenceCheck: true,
    brepRemoveLevel: 2,
    brepRemoveSize: 2,
    holeRemoveDiagonalTolerance: 0.05,
    holeRemoveRangeTolerance: 0.02,
    holeRemoveVolumeTolerance: 0.005,
    internalFacesRemoveAngleTolerance: 0.28,
    internalFacesRemoveLinearTolerance: 0.01,
    smallBodiesRemoveThreshold: 0.1,
    smallBodiesRemoveLinearTolerance: 0.01,
    internalFacesRemoveInvisibleRemove: true,
    smallBodiesRemoveVisualQualityAware: true,
    advanceSimplify: true,
    simplifyInit: true,
    remark: '测试一哈',
    modelName: 'testMode',
    dept: 'TestDept',
    author: 'tester',
    classify: '1',
    testFile: '1-pingban-B1.CATPart',
    meshSimpleType: 1,
    meshSimpleLevel: 2,
    meshSimpleValue: 7500,
    meshSimpleForce: false,
    isPreferredLOD: false,
    polyPreferredLOD: 2,
    simplify: false,
    holeRemoverSimplify: false,
    internalFacesRemoverSimplify: false,
    smallBodiesSimplify: false,
    meshSimplify: false,
  });
  /*const fileList = ref<FileItem[]>([]);*/
  const supportBrepSimplify = ref(true);
  const supportMeshSimplify = ref(true);
  // const {loading, setLoading} = useLoading();

  // 提交状态
  const loading = ref<boolean>(false);

  // 表单验证规则
  const formRules = reactive({
    testFile: [{ required: true, message: '请填写测试文件', type: 'string', trigger: 'blur' }],
    modelName: [{ required: true, message: '请填写模型名称', type: 'string', trigger: 'blur' }],
    classify: [{ required: true, message: '请选择资产分类', type: 'string', trigger: 'blur' }],
    dept: [{ required: true, message: '请填写资产所属', type: 'string', trigger: 'blur' }],
    author: [{ required: true, message: '请填写作者', type: 'string', trigger: 'blur' }],
    remark: [{ required: true, message: '请填写备注', type: 'string', trigger: 'blur' }],
  });

  /*const onUploadSuccess = (res: FileItem) => {
    if (res.response?.code !== 200) {
      message.error(res.response.message);
      setTimeout(() => {
        fileList.value = fileList.value.filter((item) => item.uid !== res.uid);
      });
    }
  };*/

  /*const onSubmitClick = async () => {
    const err = await formRef.value?.validate();
    if (!err) {
      // setLoading(true);
      // 修改加载框为正在加载
      loading.value = true;
      try {
        const fd = new FormData();
        Object.entries(formData.value).forEach(([name, value]) => {
          fd.append(name, value as any);
        });

        const res = await ModelMgmtApi.add(fd);
        if (res.success) {
          message.success('新增保存成功!');
          router.back();
        } else {
          message.error(res.message);
        }
      } finally {
        // setLoading(false);
        // 移除加载框
        loading.value = false;
      }
    }
  };*/
  // 保存
  const onSubmitClick = () => {
    // 校验表单
    formRef.value.validate().then(async (valid) => {
      if (valid) {
        // 修改加载框为正在加载
        loading.value = true;

        /*try {*/
          const fd = new FormData();
          Object.entries(formData.value).forEach(([name, value]) => {
            fd.append(name, value as any);
          });

          /*const res = await ModelMgmtApi.add(fd);
          if (res.success) {
            message.success('新增保存成功!');

            // 关闭弹框，通过控制visible的值，传递给父组件
            updateVisible(false);
            emits('done');
          } else {
            message.error(res.message);
          }*/

          let res = null;
          res = ModelMgmtApi.add(fd);
          res.then((res) => {
            // 移除加载框
            loading.value = false;

            if (res.success) {
              message.success('新增保存成功，请稍后手动刷新查看结果!!');

              // 关闭弹框，通过控制visible的值，传递给父组件
              updateVisible(false);
              emits('done');
            } else {
              message.error(res.message);
            }
          }).catch(() => {
            loading.value = false;
          });

        /*} finally {
          // 移除加载
          loading.value = false;
        }*/

      }
    });
  };
</script>

<style scoped lang="less">
  .full-modal {
    .ant-modal {
      max-width: 100%;
      top: 0;
      padding-bottom: 0;
      margin: 0;
    }
    .ant-modal-content {
      display: flex;
      flex-direction: column;
      height: calc(100vh);
    }
    .ant-modal-body {
      flex: 1;
    }
  }
  :deep(.ant-drawer-body) {
    padding: 10px 24px 24px 24px;
  }
  .card-title {
    border-left: 5px solid;
    border-color: #009688;
    padding-left: 10px;
  }
  .card-title-background {
    background-color: #f4f4f4;
    height: 2em;
    line-height: 2em;
    margin-bottom: 1em;
  }
</style>
